/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    void traversal(TreeNode* root, int tmp, int& ret)
    {
        if (nullptr == root)
            return;
        if (nullptr == root->left && nullptr == root->right)
        {
            tmp = tmp * 2 + root->val;
            ret += tmp;
            return;
        }
        
        traversal(root->left, tmp * 2 + root->val, ret);
        traversal(root->right, tmp * 2 + root->val, ret);
    }
public:
    int sumRootToLeaf(TreeNode* root) {
        int ret = 0, tmp = 0;
        traversal(root, tmp, ret);
        return ret;
    }
};
